package com.kingwang.demo.springsecuritytokendemo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * TokenSession定时清理器
 */
@Component
@ConditionalOnBean(value = TokenSessionManager.class)
@EnableScheduling
@EnableAsync
public class TokenSessionScheduleCleaner {

    private TokenSessionManager sessionManager;

    @Autowired
    public TokenSessionScheduleCleaner(TokenSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    @Async
    @Scheduled(fixedDelayString = "${session.clean.intervalMillis}")
    public void cleanTokenSession() {
        Collection<TokenSession> sessions = this.sessionManager.getSessions();

        for (TokenSession item : sessions) {
            if (this.sessionManager.isExpired(item)) {
                this.sessionManager.removeSession(item);
            }
        }
    }
}
